package com.deepfos.outreach.util;

import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.OkHttps;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public final class HttpUtil {
    private static final HTTP http = HTTP.builder()
            .config((OkHttpClient.Builder builder) -> {
                // 配置连接池 最小10个连接（不配置默认为 5）
                builder.connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES));
                // 连接超时时间（默认10秒）
                builder.connectTimeout(10, TimeUnit.SECONDS);
                // 写入超时时间（默认10秒）
                builder.writeTimeout(10, TimeUnit.SECONDS);
                // 读取超时时间（默认10秒）
                builder.readTimeout(10, TimeUnit.SECONDS);
            })
            .bodyType(OkHttps.JSON)
            .build();

    public static String pushJSONBody(String reqJSONData, String url, String username, String password) {
        Headers headers = Headers.of(new HashMap<String, String>() {{
            put("content-type", "application/json;charset=UTF-8");
            if ((Objects.nonNull(username) && Objects.isNull(password)) || (Objects.nonNull(username) && Objects.nonNull(password))) {
                put("Authorization", Credentials.basic(username, password));
            }
        }});

        Date requestTime = new Date();
        Request request = new Request.Builder()
                .url(url)
                .headers(headers)
                .post(RequestBody.create(null, reqJSONData))
                .build();
        Response response = null;
        try {
            response = http.request(request).execute();
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(String.format("请求三方接口：{1}，报：{0}", ex, url));
        }
        Headers headers1 = response.headers();
        String responseBody = null;
        try {
            responseBody = response.body().string();
        } catch (IOException ex) {
            ex.printStackTrace();
            log.error(String.format("处理三方接口返回信息：{1}，报：{0}", ex, response.body()));
        }
        log.info(String.format("三方接口返回状态为 ：%s", response.isSuccessful()));

        Date responseTime = new Date();

        if (log.isDebugEnabled()) {
            log.debug(String.format("调用三方接口耗时：%d ms\nrequest: \nheader: \n%s \n body: \n%s \nresponse: \nheader: \n%s \n body: \n%s \n", responseTime.getTime() - requestTime.getTime(), request.headers(), reqJSONData, headers1, responseBody));
        }

        return responseBody;
    }
}
